class CalendarController < ApplicationController
  before_filter :login_required
  
  
  def index
  end
  
  def select_project
    p_id = params[:id]
    if(p_id == nil || p_id == "undefined")
      @events = Calendar.find(:all, :conditions => "user_id=#{session['user']['id']}", :order=>'date')#.sort_by {|c| if(c.date==nil) then [Date.today()] else [c.date] end }
      msg = 'Displaying all <b>your</b> events'
    else
      @events = Calendar.find(:all, :conditions => "project_id=#{p_id}", :order=>'date')#.sort_by {|c| if(c.date==nil) then [Date.today()] else [c.date] end }
      msg = 'Displaying <b>project</b> events'
    end
    render(:partial=>'events', :locals=>{:msg=>msg})
  end
  
  def create
    p_id = params[:new][:project_id]
    if(p_id=='')
      render(:text=>'You have to select a project')
      return
    end
    c = Calendar.new(params[:new])
    c.project_id = -1 if p_id == ''
    c.user_id = session['user']['id']
    c.save
    @events = Calendar.find(:all, :conditions => "project_id=#{p_id}").sort_by {|c| if(c.date==nil) then [Date.today()] else [c.date] end }
    render(:partial=>'events', :locals=>{:msg=>''})
  end
  
  # Ajaxed
  def delete
    id = params[:id]
    begin
      t = Calendar.find(id)
      rescue Exception => e
      t = nil
    end
    render(:text=>'-1') and return if t == nil or (t.user_id != 0 and t.user_id != session['user']['id'])
    # or (t.project_id) TODO: add something to verify if the event is on a project we are member of
    # t.user_id != 0 # commented so we can delete old events that had no user_id at the time of creation (old version of PTM)
    if Calendar.destroy(id)
      render(:text=>"#{id}")
    else
      render(:text=>'-1')
    end
  end
  
end
